<template>
    <el-card>
        <el-form class="flex">
            <el-form-item label="角色名称">
                <el-input placeholder="角色名称" v-model="keyword"></el-input>
            </el-form-item>
            <el-form>
                <el-button type="primary" :disabled="!keyword" @click="search">
                    搜索
                </el-button>
                <el-button @click="reset">重置</el-button>
            </el-form>
        </el-form>
    </el-card>
    <el-card class="base-margin">
        <el-form>
            <el-form-item>
                <el-button type="primary" icon="Plus" @click="addRole">
                    添加角色
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-table border :data="RoleList">
                    <el-table-column
                        label="#"
                        type="index"
                        align="center"
                    ></el-table-column>
                    <el-table-column
                        label="id"
                        align="center"
                        prop="id"
                    ></el-table-column>
                    <el-table-column
                        label="角色名称"
                        align="center"
                        prop="roleName"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                        label="创建时间"
                        align="center"
                        prop="createTime"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                        label="更新时间"
                        align="center"
                        prop="updateTime"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column label="操作" align="center" width="400">
                        <template #="{ row }">
                            <el-button
                                type="primary"
                                icon="Setting"
                                size="small"
                                @click="doAssign(row)"
                            >
                                分配权限
                            </el-button>
                            <el-button
                                type="primary"
                                icon="Edit"
                                size="small"
                                @click="updataRole(row)"
                            >
                                编辑
                            </el-button>

                            <el-popconfirm
                                title="Are you sure to delete this?"
                                @confirm="deleteRole(row)"
                            >
                                <template #reference>
                                    <el-button
                                        type="primary"
                                        icon="Delete"
                                        size="small"
                                    >
                                        删除
                                    </el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
        </el-form>
        <el-pagination
            @change="getRoleList"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 7, 9, 11]"
            background
            layout=" prev, pager, next, jumper,->,total, sizes"
            :total="total"
            class="base-margin"
        />
    </el-card>
    <el-dialog
        :title="RoleParams.id ? '编辑角色' : '添加角色'"
        v-model="dialogVisible"
    >
        <el-form :model="RoleParams" :rules="rules" ref="ruleFormRef">
            <el-form-item label="角色名称" prop="roleName">
                <el-input
                    placeholder="请输入角色名称"
                    style="width: 200px"
                    v-model="RoleParams.roleName"
                ></el-input>
            </el-form-item>
            <el-form-item>
                <div class="flex-end">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="comfirm">确定</el-button>
                </div>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-drawer v-model="drawer" title="分配权限">
        <template #default>
            <el-tree
                ref="tree"
                style="max-width: 600px"
                :data="data"
                show-checkbox
                node-key="id"
                default-expand-all
                :default-checked-keys="selectArr"
                :props="defaultProps"
            />
        </template>
        <template #footer>
            <el-button @click="cancelAssign">取消</el-button>
            <el-button type="primary" @click="confirmAssign">确定</el-button>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue';
import { useSettingStore } from '@/store/modules/setting';
import {
    reqGetRoleList,
    reqAddOrUpdateRole,
    reqDeleteRole,
    reqGetRoleDetail,
    reqAssignPermission,
} from '@/api/acl/role';
import type { Records, MenuList, MenuResponseData } from '@/api/acl/role/type';
import { ElMessage } from 'element-plus';
const currentPage = ref<number>(1); // 当前页数
const pageSize = ref<number>(5); // 每页显示的条数
const total = ref<number>(0); // 总条数
const RoleList = ref<Records[]>([]);
const keyword = ref<string>('');
const dialogVisible = ref(false);
const settingStore = useSettingStore();
const ruleFormRef = ref();
const drawer = ref(false);
const tree = ref();
// 树形结构展示字段
const defaultProps = {
    children: 'children',
    label: 'name',
};
const data = ref<MenuList[]>([]);
//  准备一个数组:存储已有权限的 id
const selectArr = ref<number[]>([]);
// 收集数据
const RoleParams = reactive<Records>({
    roleName: '',
});
onMounted(() => {
    getRoleList();
});
const getRoleList = async () => {
    // 获取用户列表
    const res = await reqGetRoleList(
        currentPage.value,
        pageSize.value,
        keyword.value,
    );
    if (res.code === 200) {
        RoleList.value = res.data.records;
        total.value = res.data.total;
    }
};
// 搜索
const search = () => {
    getRoleList();
    keyword.value = '';
};
const reset = () => {
    settingStore.refresh = true;
};
// 添加
const addRole = () => {
    dialogVisible.value = true;
    RoleParams.roleName = '';
    RoleParams.id = '';
    // 表单校验重置
    nextTick(() => {
        ruleFormRef.value.clearValidate('roleName');
    });
};
// 编辑角色
const updataRole = (row: Records) => {
    dialogVisible.value = true;
    RoleParams.id = row.id;
    RoleParams.roleName = row.roleName;
};
// 取消
const cancel = () => {
    dialogVisible.value = false;
    nextTick(() => {
        ruleFormRef.value.clearValidate('roleName');
    });
};
// 确认添加
const comfirm = async () => {
    await ruleFormRef.value.validate();
    const res = await reqAddOrUpdateRole(RoleParams);
    if (res.code === 200) {
        ElMessage.success('成功');
        dialogVisible.value = false;
        getRoleList();
    }
};
// 删除某一角色
const deleteRole = async (row: Records) => {
    const res = await reqDeleteRole(row.id as number);
    if (res.code === 200) {
        ElMessage.success('删除成功');
        getRoleList();
    }
};
// 表单校验
const rules = reactive({
    roleName: [{ required: true, min: 2, max: 10, trigger: 'blur' }],
});
//  分配权限
const doAssign = async (row: Records) => {
    Object.assign(RoleParams, row);
    const res: MenuResponseData = await reqGetRoleDetail(row.id as number);
    if (res.code === 200) {
        drawer.value = true;
        data.value = res.data;
        selectArr.value = filterSelectArr(data.value, []);
    }
};
const filterSelectArr = (allData: any, initArr: any) => {
    allData.forEach((item: any) => {
        if (item.select && item.level === 4) {
            initArr.push(item.id);
        }
        if (item.children && item.children.length > 0) {
            filterSelectArr(item.children, initArr);
        }
    });
    return initArr;
};
const cancelAssign = () => {
    drawer.value = false;
};
const confirmAssign = async () => {
    let roleId = RoleParams.id;
    let arr = tree.value.getCheckedKeys();
    let arr1 = tree.value.getHalfCheckedKeys();
    let permissionId = [...arr, ...arr1];
    const res = await reqAssignPermission(roleId as number, permissionId);
    if (res.code === 200) {
        drawer.value = false;
        ElMessage.success('分配成功');
        reset();
    } else {
        ElMessage.error('分配失败');
    }
};
</script>

<style scoped>
.flex {
    display: flex;
    justify-content: space-between;
}

.flex-end {
    width: 100%;
    display: flex;
    justify-content: end;
}
</style>
